<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Middleware;

use Hyperf\Context\Context;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Hyperf\Redis\Redis;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use RedisException;

class AuthMiddleware implements MiddlewareInterface
{
    protected ContainerInterface $container;

    protected RequestInterface $request;

    protected HttpResponse $response;

    public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request)
    {
        $this->container = $container;
        $this->response = $response;
        $this->request = $request;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        if ($this->request->hasHeader('token') && $this->request->header('token') != '') {
            try {
                $redis = $this->container->get(Redis::class);
                $tokenInfo = $redis->hGetAll('token:' . $this->request->header('token'));
                if ($tokenInfo) {
                    Context::set('userid', (int)$tokenInfo['userid']);
                    Context::set('username', $tokenInfo['username']);
                    Context::set('mobile', $tokenInfo['mobile']);
                    Context::set('email', $tokenInfo['email']);
                    Context::set('roleId', (int)$tokenInfo['roleId']);
                    return $handler->handle($request);
                }
            } catch (ContainerExceptionInterface|NotFoundExceptionInterface|RedisException $e) {
            }
        }

        return $this->response->json(
            [
                'code' => 403,
                'msg' => '请登录后操作',
            ]
        );
    }
}
